/*
 * Copyright 2009 Prime Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.primefaces.optimus.filter;

import java.io.CharArrayWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringBufferInputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;

public class PDFRenderingFilter implements Filter {

	public void destroy() {
		
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		String asPDF = req.getParameter("asPDF");
		
		if(req.getParameter("asPDF") != null && Boolean.valueOf(asPDF) == true) {
			HttpServletResponse response = (HttpServletResponse) resp;
			BufferedResponseWrapper responseWrapper = new BufferedResponseWrapper(response);
			
			chain.doFilter(req, responseWrapper);
			
			String output = responseWrapper.toString();
			String filename = req.getParameter("filename");
			
			response.setContentType("application/pdf");
	        response.setHeader("Content-disposition", "attachment;filename=" + filename + ".pdf");
	    
	        try {
	        	DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
	            Document doc = builder.parse(new StringBufferInputStream(output));
	            ITextRenderer renderer = new ITextRenderer();
	            renderer.setDocument(doc, null);
	            renderer.layout();
	            OutputStream os = response.getOutputStream();
	            renderer.createPDF(os);
	            os.flush();
	            os.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
		} else {
			chain.doFilter(req, resp);
		}

	}

	public void init(FilterConfig filterConfig) throws ServletException {
		
	}
	
	static class BufferedResponseWrapper extends HttpServletResponseWrapper {
		
		private CharArrayWriter writer;
		
		public BufferedResponseWrapper(HttpServletResponse response) {
			super(response);
			writer = new CharArrayWriter();
		}

		public PrintWriter getWriter() throws IOException {
			return new PrintWriter(writer);
		}
		
		public String toString() {
		      return writer.toString();
		}
	}

}